<?php


namespace app\cuisine\controller;


use app\cuisine\model\IndexModel;
use cmf\controller\AdminBaseController;

class IndexController extends AdminBaseController
{
    //显示导航菜单
    public function index(){
        //获取搜索字段
        $key = input('key');
        $where = [];
        if($key){
            $where[] = ['name','like','%'.$key.'%'];
        }
        //查询
        $list = IndexModel::with('child')
            ->order('list_order','DESC')
            ->where($where)
            ->paginate(10);
        return $this->fetch('index',[
            'list'=>$list,
        ]);
    }
    //添加
    public function add(){
        $list = IndexModel::select();
        return $this->fetch('add',[
            'list' => $list
        ]);
    }
    public function addPost(){
        //获取数据
        $data = input('post.');
        //判断
        if(!$data['name']){
            $this->error('导航菜单不能为空');
        }
        if(!$data['url']){
            $this->error('跳转链接不能为空');
        }
        if($data['parent_id'] == ''){
            $this->error('父级菜单不能为空');
        }
        //入库 判断成功
        if(IndexModel::create($data)){
            $this->success('添加成功','Index/index');
        }else{
            $this->error('添加失败');
        }
    }
    //编辑
    public function edit(){
        $id = input('id');
        $list = IndexModel::find($id);
        return $this->fetch('edit',[
            'list' => $list
        ]);
    }
    public function editPost(){
        //获取数据
        $data = input('post.');
        if(!$data['name']){
            $this->error('导航菜单不能为空');
        }
        if(!$data['url']){
            $this->error('跳转链接不能为空');
        }
        if($data['parent_id'] == ''){
            $this->error('父级菜单不能为空');
        }
        //入库 判断成功
        if(IndexModel::update($data)){
            $this->success('保存成功','Index/index');
        }else{
            $this->error('保存失败');
        }
    }
    //单条删除
    public function delete(){
        $id = input('id/d','');
        $isExist = IndexModel::find($id);
        //判断该id是否存在
        if(!$isExist){
            $this->error('该数据不存在');
        }
        $del = IndexModel::destroy($id);
        if($del){
            $this->success('删除成功','Index/index');
        }else{
            $this->error('删除失败');
        }
    }
}